import os
from io import BytesIO

import requests


class WeChatAPI:
    CORPID = "wwbeea980e98f19412"
    CORPSECRET = "D7nA3KTKihVavDNJhqDsvYeByG6gBO2ld7w3NkKeT4M"
    AGENTID = 1000002

    def __init__(self):
        self.access_token = None
        try:
            self.access_token = self.get_access_token()
        except Exception as e:
            print(e)
            print("token获取失败")

    def get_access_token(self):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={WeChatAPI.CORPID}&corpsecret={WeChatAPI.CORPSECRET}"
        response = requests.get(url)
        data = response.json()
        if data.get("errcode") == 0:
            return data.get("access_token")
        else:
            raise Exception(f"Failed to get access_token: {data}")

    def get_department_list(self):
        """
        获取企业微信部门信息
        """
        url = f'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={self.access_token}'
        response = requests.get(url)
        data = response.json()
        if data.get("errmsg") != "ok":
            return False
        return data.get("department")

    def get_wechat_user_list(self, department_id):
        """
        获取部门用户信息列表
        department_id： 部门id
        """
        url = f"https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={self.access_token}&department_id={department_id}"
        response = requests.get(url)
        data = response.json()
        print(data)
        if data.get("errmsg") != "ok":
            return False
        return data.get("userlist")

    def create_wechat_group(self, name, owner, userlist):
        """
        创建微信群
        name：群名称
        owner： 群主
        userlist： 群成员id列表
        """
        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={self.access_token}"
        payload = {
            "name": name,
            "owner": owner,
            "userlist": userlist
        }
        response = requests.post(url, json=payload)
        data = response.json()
        if data.get("errmsg") != "ok":
            raise Exception(f"Failed to create group chat: {data}")
        else:
            return data.get("chatid")

    def send_wechat_message(self, wechat_group_id, message):
        """
        企业微信群发消息
        wechat_group_id: 群id
        message_type：消息类型
        message： 消息内容
        """
        payload = {
            "chatid": wechat_group_id,
            "msgtype": "text",
            "text": {
                "content": message
            }
        }
        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={self.access_token}"
        response = requests.post(url, json=payload)
        data = response.json()
        print(data)
        if data.get("errmsg") != "ok":
            raise Exception(f"Failed to create group chat: {data}")
        else:
            return data.get("chatid")

    def upload_file(self, file_path):
        """
        上传文件到企业微信服务器
        file_path: 文件路径
        """

        file_type = "file"
        url = f"https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={self.access_token}&type={file_type}"
        with open(file_path, 'rb') as f:
            file_content = f.read()
        file_stream = BytesIO(file_content)
        filename = os.path.basename(file_path)
        files = {'media': (filename, file_stream, 'application/octet-stream')}
        response = requests.post(url, files=files)
        data = response.json()
        print(data)
        if data.get("errmsg") != "ok":
            raise Exception(f"Failed to create group chat: {data}")
        else:
            return data.get("media_id")

    def _validate_chatid(self, chatid):
        """验证群聊ID有效性"""
        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/get?access_token={self.access_token}&chatid={chatid}"
        try:
            resp = requests.get(url, timeout=5).json()
            return resp.get('errcode') == 0
        except:
            return False

    def send_file_to_group(self, chatid, file_path):
        if not self._validate_chatid(chatid):
            print(f"无效群聊ID: {chatid}")
            return {"errcode": -1, "errmsg": "Invalid ChatID"}
        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={self.access_token}"
        media_id = self.upload_file(file_path)
        print(media_id)
        data = {
            "chatid": chatid,
            "msgtype": "file",
            "agentid": WeChatAPI.AGENTID,
            "file": {
                "media_id": media_id
            }
        }
        response = requests.post(url, json=data)
        print(response.json())
        return response.json()




if __name__ == "__main__":

    wechat_api = WeChatAPI()
    group_name = "20250318测试"
    owner = "ChenRongBo"
    userid_list = ["ChenRongBo", "WeiMeiQuan"]
    # chatid = wechat_api.create_wechat_group(group_name, owner, userid_list)
    chatid = "wr8HbdZQAAEuQ0uRL5dUXNed_kTAUmcQ"
    print(chatid)
    # wechat_api.get_department_list()
    file_path = r"C:\Users\Administrator\Desktop\测试企业微信发送文件.xlsx"
    # wechat_api.upload_file(file_path)
    wechat_api.send_file_to_group(chatid, file_path)



